import { mapMutations } from 'vuex';

/**
 * @field 登录页说明
 * @author zhouqin(zhouqin12@sfmail.sf-express.com)
 * @date 2021-06-20
 * @version v.1.0
 */
export default {
    name: 'Login',
    data() {
        // 供应商编码
        let validateUserName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入供应商号码'));
            } else {
                callback();
            }
        };
        // 供应商密码
        let validatePassword = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入供应商密码'));
            } else {
                callback();
            }
        };
        // 手机号
        var validatePhoneNumber = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入手机号'));
            } else {
                callback();
            }
        };
        // 验证码
        let validateVertifyCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('验证码不能为空'));
            } else {
                callback();
            }
        };
        return {
            //
            imgCode: '',
            activeLog: 'accont',
            accountOrPhoneFlag: true,
            kaptchaToken: '',
            accountForm: {
                // 供应商手机号
                username: '',
                // 供应商密码
                password: ''
            },
            phoneForm: {
                // 手机号
                phoneNumber: '',
                // 验证码
                vertifyCode: '',
                // 图形验证码
                imgCode: ''
            },
            accontRules: {
                // 供应商手机号
                username: [{ validator: validateUserName, trigger: 'blur' }],
                // 供应商密码
                password: [{ validator: validatePassword, trigger: 'blur' }]
            },
            phoneRules: {
                phoneNumber: [{ validator: validatePhoneNumber, trigger: 'blur' }],
                vertifyCode: [{ validator: validateVertifyCode, trigger: 'blur' }]
            }
        };
    },
    mounted() {
        this.getImgCode();
    },
    methods: {
        ...mapMutations(['setUserName', 'setSupplierCode']),
        tabLogHandle() {
            console.log('tab');
        },
        // 点击刷新图形验证码
        handleImgCode() {
            this.getImgCode();
        },
        // 图形验证码生成
        getImgCode() {
            // h5
            let self = this;
            let windowUrl = window.URL || window.webkitURL; //处理浏览器兼容性
            let xhr = new XMLHttpRequest();
            let url = process.env.VUE_APP_BASE_URL + 'api/kaptcha/defaultKaptcha';
            console.log(url, 1112222);
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (this.status === 200) {
                    let res = this.response;
                    self.kaptchaToken = this.getResponseHeader('kaptcha-token');
                    console.log(this.kaptchaToken, 'kaptchaToken');
                    console.log(res, 'blob');
                    self.imgCode = windowUrl.createObjectURL(res);
                }
            };
            xhr.send();
        },
        // 获取手机验证码
        getVertifyCode() {
            if (!this.phoneForm.phoneNumber && !this.kaptchaToken && !this.phoneForm.imgCode) {
                this.$message({
                    message: '请先填写图形验证码',
                    type: 'error'
                });
                return;
            }
            let params = {
                phone: this.phoneForm.phoneNumber, // 手机号
                captcha: this.phoneForm.imgCode, // 短信验证码
                kaptchaToken: this.kaptchaToken // 图形验证码
            };
            this.$httpExt()
                .post('/api/api/kaptcha/sendSmsCaptcha', params)
                .then(response => {
                    this.$message({
                        type: 'info',
                        message: response.message
                    });
                });
        },
        // 账号登录
        submitAccontForm(accountForm) {
            this.$refs[accountForm].validate(async valid => {
                if (valid) {
                    // 登录接口
                    const rsaPassWord = this.$generateRsaCode(this.accountForm.password);
                    this.$httpExt()
                        .post('/api/login/user', {
                            username: this.accountForm.username,
                            password: rsaPassWord
                        })
                        .then(
                            async response => {
                                console.log('响应', response);
                                // this.getCurrentUserInfo(response.data);
                                this.$router.push('/home');
                                const { data } = await this.$httpExt().get('/api/common/getCurrentUserInfo', {
                                    token: response.data
                                });
                                this.setUserName(data?.username);
                                this.setSupplierCode(data?.supplierCode);
                            },
                            response => {
                                this.checkFirstLogin(response);
                            }
                        );
                } else {
                    this.$message({
                        message: '登录失败',
                        type: 'error'
                    });
                }
            });
        },
        // 手机号登陆
        submitPhoneForm(phoneForm) {
            this.$refs[phoneForm].validate(async valid => {
                if (valid) {
                    // 登录接口
                    this.$httpExt()
                        .post('/api/login/phone', {
                            phone: this.phoneForm.phoneNumber,
                            smsCaptcha: this.phoneForm.vertifyCode
                        })
                        .then(
                            async response => {
                                console.log('响应', response);
                                // this.getCurrentUserInfo(response.data);
                                this.$router.push('/home');
                                const { data } = await this.$httpExt().get('/api/common/getCurrentUserInfo', {
                                    token: response.data
                                });
                                this.setUserName(data?.username);
                                this.setSupplierCode(data?.supplierCode);
                            },
                            response => {
                                this.checkFirstLogin(response);
                            }
                        );
                } else {
                    this.$message({
                        message: '登录失败',
                        type: 'error'
                    });
                }
            });
        },
        /**
         * 检查是否首次登陆
         */
        checkFirstLogin(response) {
            console.log('检查是否第一次登录：', response);
            if (response.code === '0004P002') {
                sessionStorage.setItem('token', response.data);
                this.$router.push({ name: 'ChangeScret' });
                return false;
            }

            return true;
        }
    }
};
